package com.applications.codemash.core.eventhandlers;

import com.applications.codemash.R;
import com.applications.codemash.core.BaseActivity;
import com.applications.codemash.core.Session;
import com.applications.codemash.utility.CustomListAdapter;

import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.ViewFlipper;

public class FlingGestureDetector extends SimpleOnGestureListener
{
	private ViewFlipper _flipper;
	private BaseActivity _activity;
	
	private static final int MINIMUM_GESTURE_DISTANCE = 50;
	
	public FlingGestureDetector(ViewFlipper flipper, BaseActivity activity)
	{
		_flipper = flipper;
		_activity = activity;
	}
	
	@SuppressWarnings("unchecked")
	@Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
		int dx = (int)(e2.getX() - e1.getX());
        if (Math.abs(dx) > MINIMUM_GESTURE_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY))
        {
        	if (velocityX > 0)
            {
        		_flipper.setInAnimation(AnimationUtils.loadAnimation(_activity, R.anim.slide_right_in));
                _flipper.setOutAnimation(AnimationUtils.loadAnimation(_activity, R.anim.slide_right_out));
                _flipper.showNext();
            }
            else
            {
            	_flipper.setInAnimation(AnimationUtils.loadAnimation(_activity, R.anim.slide_left_in));
                _flipper.setOutAnimation(AnimationUtils.loadAnimation(_activity, R.anim.slide_left_out));
                _flipper.showPrevious();
            }
        	
        	View view = _flipper.getChildAt(_flipper.getDisplayedChild());
        	CustomListAdapter<Session> sessionAdapter = (CustomListAdapter)((ListView)view.findViewById(R.id.listView)).getAdapter();
            _activity.setWindowTitle(sessionAdapter.getData().get(0));
            
            return true;
        }
    
        return false;
    }
}